package com.fbli.Thread.syn;

/**
 * 模拟线程死锁
 */
public class DeadLock_ {

    public static void main(String[] args) throws InterruptedException {
        DeadLockDemo A = new DeadLockDemo(true);
        DeadLockDemo B = new DeadLockDemo(false);
        DeadLock_ deadLock_ = new DeadLock_();
        A.setName("A");
        B.setName("B");
        A.start();
        B.start();
    }
}
class DeadLockDemo extends Thread{
    static Object o1 = new Object();//保证多个线程共用一个变量，
    static Object o2 = new Object();
    private boolean flag;
    public DeadLockDemo(boolean flag){
        this.flag = flag;
    }

    @Override
    public void run() {
        /**
         * 1.如果flag 为 T ，线程A就会先得到/持有 o1对象锁，然后尝试去获取o2对象锁
         * 2.如果线程A得不到o2对象锁，就会Blocked
         * 3.如果flag为 F,线程B就会先得到/持有 o2对象锁，然后尝试获取o1对象锁
         * 4.如果线程B 得不到o1对象锁，就会Blocked
         */
        if (flag){
            synchronized (o1){//对象互斥锁，下面是同步代码块
                System.out.println(Thread.currentThread().getName()+"进入1");
                synchronized (o2){//这里获得li对象的监视权
                    System.out.println(Thread.currentThread().getName()+ "进入2");
                }
            }
        }else {
            synchronized (o2){//对象互斥锁，下面是同步代码块
                System.out.println(Thread.currentThread().getName()+"进入3");
                synchronized (o1){//这里获得li对象的监视权
                    System.out.println(Thread.currentThread().getName()+ "进入4");
                }
            }
        }
    }
}